# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: inkyu

import re

from datetime import datetime
from pymongo import MongoClient


class HkParser(object):
  def __init__(self, db_name, *, on_push, dry_run=False):
    self._storage = {}
    self._db_name = db_name
    self._db = MongoClient(
        'mongodb://inkyu_legacy:xArT3T#dXtGfSBDV@13.251.33.84:42006/coin_20181121'
    ).legacy_20181201[db_name]
    self._pnl = MongoClient(
        'mongodb://inkyu_legacy:xArT3T#dXtGfSBDV@13.251.33.84:42006/coin_20181121'
    ).pnl_20181201[db_name]
    self._timestamp = None
    self._state = 0
    self._krw = None
    self._usdt = None
    self._on_push = on_push
    self._dry_run = dry_run

  def _push_legacy(self, payload):
    self._on_push(self._db_name, 'chart', payload)
    if not self._dry_run:
      self._db.insert_one(payload)

  def _push_pnl(self, payload):
    self._on_push(self._db_name, 'pnl', payload)
    if not self._dry_run:
      self._pnl.insert_one(payload)

  def handle(self, line):
    if line.startswith('* 2018'):
      try:
        self._timestamp = datetime.strptime(line[2:-1], '%Y-%m-%d %H:%M:%S.%f')
      except Exception:
        pass
      self._storage['timestamp'] = self._timestamp
    elif line.startswith(' USDT: '):
      splitted = re.split('\ +', line)
      self._krw = float(splitted[2][:-1])
      self._usdt = float(splitted[4][:-1])
    elif line.startswith('Position'):
      splitted = re.split('\ +', line)
      dkrw = float(splitted[4])
      dusdt = float(splitted[1])
      if dkrw != 0:
        self._push_legacy({
            'timestamp': self._timestamp,
            'tag': 'USDT',
            'value': self._krw + dkrw + self._usdt + dusdt
        })
        self._storage['usdt_pass'] = self._krw
        self._storage['usdt_agg'] = self._usdt
        self._storage['usdt_pass_pos'] = dkrw
        self._storage['usdt_agg_pos'] = dusdt
    elif line.startswith('Balance'):
      splitted = re.split('\ +', line)
      dkrw = float(splitted[3])
      dusdt = float(splitted[1])
      if dkrw != 0:
        self._storage['usdt_pass_bal'] = dkrw
        self._storage['usdt_agg_bal'] = dusdt
    elif line.startswith('Reserve'):
      splitted = re.split('\ +', line)
      dkrw = float(splitted[3])
      dusdt = float(splitted[1])
      if dkrw != 0:
        self._storage['usdt_pass_reserve'] = dkrw
        self._storage['usdt_agg_reserve'] = dusdt
    elif line.startswith('MasterPrices'):
      splitted = re.split('[ ()=]+', line)
      gmean_price = float(splitted[2][:-1])
      ema_price = float(splitted[4][:-1])
      self._storage['ema_price'] = ema_price
      self._storage['gmean_price'] = gmean_price
      if 'usdt_pass' in self._storage:
        self._push_pnl(self._storage)
      self._storage = {}
